package Java7_Concurrency_Cookbook.concurrent_collection_framework.concurrent_skip_list_map;

import java.util.Map;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * SkipList(跳表) 是一种数据结构.<br/>
 * ConcurrentSkipListMap.headMap(K toKey) 返回映射中所有键值小于参数值toKey的子映射<br/>
 * ConcurrentSkipListMap.tailMap(K fromKey) 返回映射中所有键值大于参数值fromKey的子映射<br/>
 * ConcurrentSkipListMap.pollLastEntry() 返回并移除映射中最后一个Map.Entry对象<br/>
 * @author lixiangke
 * @date 2017/11/24
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        ConcurrentSkipListMap<String, Contact> map = new ConcurrentSkipListMap<>();
        Thread[] threads = new Thread[25];
        int counter = 0;
        for (char i = 'A'; i < 'Z'; i++) {
            Task task = new Task(map, String.valueOf(i));
            threads[counter] = new Thread(task);
            threads[counter].start();
            counter++;
        }
        for (int i = 0; i < 25; i++) {
            threads[i].join();
        }
        System.out.printf("Main: Size of the map : " + map.size() + "\n");

        Map.Entry<String, Contact> element = map.firstEntry();
        Contact contact = element.getValue();
        System.out.printf("Main: First Entry : (%s, %s)\n", contact.getName(), contact.getPhone());

        element = map.lastEntry();
        contact = element.getValue();
        System.out.printf("Main: Last Entry : (%s, %s)\n", contact.getName(), contact.getPhone());

        System.out.printf("Main: Submap from A1996 to B1002:\n");
        ConcurrentNavigableMap<String, Contact> submap = map.subMap("A1996", "B1002");
        do {
            element = submap.pollFirstEntry();
            if (element != null) {
                contact = element.getValue();
                System.out.printf("%s: %s\n", contact.getName(), contact.getPhone());
            }
        } while (element != null);


    }
}
